import threading

import os, os.path
import sys
import time
import re 

import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)


class Runner(threading.Thread):
    
    def __init__(self):
        super(Runner, self).__init__()
        my_logger.critical('__init__ Runner')
        self.running = False
        self.line_nr = 0
        self.temp = ""
        self.gcodes = []

    def send(self, msg):
        f = os.open("/dev/testing_1", os.O_RDWR)
        os.write(f, msg+"\n")
        while True:
            ret = self.readline(f)
            if "T:" in ret:
                m = re.search('^.*(T\:\d+).*(B\:\d+).*', ret) 
                if m:
                    stat = m.group(1)+"/"+m.group(2)
                    self.temp = stat
            if "ok" in ret:
                break;
        os.close(f)
        return ret
    
    def readline(self, f):
        message = ""
        while True:
            cur_char = os.read(f, 1)
            if (cur_char == '\n' or cur_char == ""):
                return message;
            message = message + cur_char

    def run(self):
        my_logger.critical('run')
        while True:
            if self.running:
                for gcode in self.gcodes:
                    gcode = gcode.strip()
                    if ";" in gcode:
                        gcode = gcode.split(";")[0].strip()
                    if gcode != "":
                        my_logger.critical("Sending '"+gcode+"'")
                        ret = self.send(gcode+"\n")
                    self.line_nr += 1
                self.running = False
            else:
                self.send("M105\n")
                time.sleep(1)            


runner = Runner()
runner.start()

